package org.example;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        //配置规则
        initFlowRules();
        for(int i = 0; i < 30; i++){
            try(Entry entry = SphU.entry("helloworld")){
                //业务逻辑处理
                System.out.println("helloworld"+i);
            } catch (BlockException e) {
                //处理限流时的逻辑
                System.out.println("blocked" +i);
            }
        }
    }
    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("helloworld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
